package com.cskaoyan.demo.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;



/**
 * ★注意事项：使用任何一个JSON工具类都需要注意，要提供类的无参构造方法和getter/setter方法
 * 如果没有提供转换过程会报错
 */
public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static  <T> T read(String jsonStr, Class<T> clazz) {
        T t = null;
        try {
            t = objectMapper.readValue(jsonStr, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return t;
    }

    // 后续响应的时候使用
    public static String write(Object instance) {
        String jsonStr = null;
        try {
            jsonStr = objectMapper.writeValueAsString(instance);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return jsonStr;
    }
}
